#include "mesh.h"

using namespace sde;

Mesh::Mesh(std::string _type, std::string _name, Object* _object) :
    SceneNode(_type,_name,_object),
    entity(0) {
}

void Mesh::run() {
    SceneNode::run();
    
    updateMeshName(object->getVar("meshName",Var(std::string(""))));
    object->subscribeSetVar("meshName",boost::bind(&Mesh::updateMeshName,this,_1));
}

void Mesh::updateMeshName(Var val) {
    if (entity) {
        sceneNode->detachObject(entity);
        sceneManager->destroyEntity(entity);
    }
        
    std::string meshName = boost::any_cast<std::string>(val);
    if (sceneManager && meshName != "") {
    
        try {
            entity = sceneManager->createEntity(object->name,meshName);
        } catch (Ogre::Exception e) {
            log("couldn't open mesh %s: %s",meshName.c_str(),e.getFullDescription().c_str());
            entity = 0;
        }
    }
    
    if (entity && sceneNode) {
        sceneNode->attachObject(entity);
    }
}
